﻿import Vue from 'vue';
import {
    CodeToText,
    TextToCode
} from "element-china-area-data";

/**
 *  UtilService
 *  工具类
 */
export default {
    /**
     * base64转blob
     * @param {*} base64 base64字符串
     * @return url地址
     */
    excelBase64ToBlob(base64) {
        let base = atob(base64);
        let length = base.length;
        let u8arr = new Uint8Array(length);
        while (length--) {
            u8arr[length] = base.charCodeAt(length);
        }
        let blob = new Blob([u8arr], {
            type: "application/vnd.ms-excel"
        });
        return URL.createObjectURL(blob);
    },

    parseTime(time, cFormat) {
        if (arguments.length === 0) {
            return null
        }
        const format = cFormat || '{y}-{m}-{d} {h}:{i}:{s}'
        let date
        if (typeof time === 'object') {
            date = time
        } else {
            if (('' + time).length === 10) time = parseInt(time) * 1000
            date = new Date(time)
        }
        const formatObj = {
            y: date.getFullYear(),
            m: date.getMonth() + 1,
            d: date.getDate(),
            h: date.getHours(),
            i: date.getMinutes(),
            s: date.getSeconds(),
            a: date.getDay()
        }
        const time_str = format.replace(/{(y|m|d|h|i|s|a)+}/g, (result, key) => {
            let value = formatObj[key]
            if (key === 'a') return ['一', '二', '三', '四', '五', '六', '日'][value - 1]
            if (result.length > 0 && value < 10) {
                value = '0' + value
            }
            return value || 0
        })
        return time_str
    },
    /**
     * 获取下一个月
     * @date 格式为yyyy-mm-dd的日期，如：2014-01-25
     */
    getNextMonth(date) {
        var arr = date.split('-');
        var year = arr[0]; //获取当前日期的年份
        var month = arr[1]; //获取当前日期的月份
        var day = arr[2]; //获取当前日期的日
        var days = new Date(year, month, 0);
        days = days.getDate(); //获取当前日期中的月的天数
        var year2 = year;
        var month2 = parseInt(month) + 1;
        if (month2 == 13) {
            year2 = parseInt(year2) + 1;
            month2 = 1;
        }
        var day2 = day;
        var days2 = new Date(year2, month2, 0);
        days2 = days2.getDate();
        if (day2 > days2) {
            day2 = days2;
        }
        if (month2 < 10) {
            month2 = '0' + month2;
        }

        var t2 = year2 + '-' + month2 + '-' + day2;
        return t2;
    },
    /**
     * 删除base64前缀（data:image/png;base64,）
     *
     * @param {*} base64
     * @returns
     */
    removeBase64Prefix(base64) {
        let index = base64.lastIndexOf(',') + 1;
        return base64.substring(index, base64.length);
    },
    /**
     * 对象转为get请求参数字符串，即（id=1&name=张三）
     *
     * @param {*} model
     */
    modelToGetRequestParameter(model) {
        let urlStr = "";
        Object.keys(model).forEach(param => {
            if (urlStr !== "") {
                urlStr += "&";
            }
            urlStr += `${param}=${model[param]}`;
        });
        return urlStr;
    },
    /**
     * 分转元
     * @param {*} price
     * @returns
     */
    subTransfer(price) {
        let str = (price / 100).toFixed(2) + '';
        return str;
    },
    /**
     * 将数据为null的更换为字符串空
     * @param {*} data 
     */
    dataFormat(data) {
        Object.keys(data).forEach(key => {
            if (data[key] === null) {
                data[key] = "";
            }
        });
        return data;
    },
    /**
     * 获取当前时间 年、月、日、时、分、秒
     */
    getCurrentDate() {
        let date = new Date();
        return {
            year: date.getFullYear(),
            month: (date.getMonth() + 1) < 10 ? "0" + (date.getMonth() + 1) : (date.getMonth() + 1),
            day: date.getDate() < 10 ? "0" + date.getDate() : date.getDate(),
            hour: date.getHours(),
            minute: date.getMinutes(),
            second: date.getSeconds()
        };
    },
    getDate(split = "", split1 = "") {
        let date = new Date();
        let year = date.getFullYear();
        let month = (date.getMonth() + 1) < 10 ? "0" + (date.getMonth() + 1) : (date.getMonth() + 1);
        let day = date.getDate() < 10 ? "0" + date.getDate() : date.getDate();
        if (split) {
            return `${year}${split}${month}${split}${day}`;
        } else {
            return `${year}${split1}${month}${split1}${day}${split1}`;
        }
    },
    convertData(obj, type = 0) {
        let date = null;
        if (obj !== null) {
            date = new Date(obj);
        } else {
            date = new Date();
        }

        let year = date.getFullYear();
        let month = (date.getMonth() + 1) < 10 ? "0" + (date.getMonth() + 1) : (date.getMonth() + 1);
        let day = date.getDate() < 10 ? "0" + date.getDate() : date.getDate();
        let hour = date.getHours() < 10 ? "0" + date.getHours() : date.getHours();
        let minute = date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes();
        let second = date.getSeconds() < 10 ? "0" + date.getSeconds() : date.getSeconds();
        switch (type) {
            case 0:
                return `${year}年${month}月${day}日`;
                break;
            case 1:
                return `${year}年${month}月${day}日${hour}时${minute}分${second}秒`;
                break;
            case 2:
                return `${year}-${month}-${day}`;
                break;
            case 3:
                return `${year}-${month}-${day} ${hour}:${minute}:${second}`;
                break;
            case 4:
                return `${year}-${month}-${day} ${hour}:${minute}`;
                break;
            case 5:
                return `${year}/${month}/${day} ${hour}:${minute}:${second}`;
                break;
            case 6:
                return `${year}/${(date.getMonth() + 1)}/${date.getDate()} ${date.getHours()}:${date.getMinutes()}:${date.getSeconds()}`;
                break;
        }
    },
    /**
     * 地址文本转地址码
     * @param {*} args 
     */
    AddressCodeToText(args) {
        let code1 = TextToCode[args[0]].code;
        let code2 = TextToCode[args[0]][args[1]].code;
        let code3 = TextToCode[args[0]][args[1]][args[2]].code;
        return [code1, code2, code3];
    },
    /**
     * 根据生日计算年龄
     * @param {*} birthday 生日 
     */
    getAge(birthday) {
        let date = new Date();
        let currentYear = date.getFullYear();
        let oldDate = new Date(birthday);
        let oldYear = oldDate.getFullYear();
        return currentYear - oldYear;
    },
    getNumber(list, start, end, uint, defaultCheck = true) {
        for (let index = start; index <= end; index++) {
            list.push({
                key: index,
                value: `${index}${uint}`,
                check: defaultCheck ? index === start : false
            });
        }
    },
    getNumberLabel(list, start, end, uint) {
        for (let index = start; index <= end; index++) {
            list.push({
                value: index + "",
                label: `${index}${uint}`
            });
        }
    },
    getNumberName(list, start, end, uint, defaultCheck = true) {
        for (let index = start; index <= end; index++) {
            list.push({
                name: `${index}${uint}`,
                value: index,
                check: defaultCheck ? index === start : false
            });
        }
    },
    /**
     * 根据体重/身高计算BMI值
     *
     * @param {*} weight
     * @param {*} height
     * @returns
     */
    getBMI(weight, height) {
        let pow = Math.pow(height / 100, 2);
        let result = weight / pow;
        return result.toFixed(2);
    },
    handler: function(e) {
        e.preventDefault();
    },
    /*解决页面层级相互影响滑动的问题*/
    closeTouch() {
        document
            .getElementsByTagName("body")[0]
            .addEventListener("touchmove", this.handler, {
                passive: false
            }); //阻止默认事件
    },
    openTouch() {
        document
            .getElementsByTagName("body")[0]
            .removeEventListener("touchmove", this.handler, {
                passive: false
            }); //打开默认事件
    },
    /**
     * 判断字段是否为空
     * @param {*} object 
     */
    isEmpty(object) {
        if (!object || object === null || object === "" || object === undefined) {
            return false;
        }
        return true;
    },
    /**
     * 设置token
     * @param {*} obj
     */
    setToken(obj) {
        Vue.local.removeItem("tdToken");
        Vue.local.setItem("tdToken", obj);
    },
    /**
     * 设置user
     * @param {*} obj
     */
    setUser(obj = null) {
        Vue.local.removeItem("tdUser");
        Vue.local.setItem("tdUser", JSON.stringify(obj));
    },
    /**
     * 设置状态
     * @param {*} obj
     */
    setStatus(obj = null) {
        Vue.local.removeItem("tdStatus");
        Vue.local.setItem("tdStatus", obj);
    },
    /**
     * 设置cookie
     * @param {*} obj
     */
    setCookie(obj = null) {
        //cookie过期时间
        let expireTimes = 60 * 60 * 1.5;
        //cookie键
        let cookie_key = "tdCookie";
        //cookie值，随机生成
        let cookie_value = "cookieStatus";
        Vue.cookies.remove("tdCookie");
        Vue.cookies.set(cookie_key, cookie_value, expireTimes);
    }
    /**
     * 判断是否中文
     * @param {*} object 
     */
    // isChinese(object) {
    //   let entryValue = object;
    //   let cnChar = entryValue.match(/[^\x00-\x80]/g);
    //   if (cnChar !== null && cnChar.length > 0) {
    //     return true;
    //   }
    //   return false;
    // },
    /**
     * 获取汉子拼音
     * @param {*} object 要转换的汉字
     * @param {*} objectSplit 拼音分割符
     * @param {*} isUppercase 是否大写
     */
    // getPinYin(object, objectSplit = " ", isUppercase = false) {
    //   let len = object.length;
    //   let result = "";
    //   let reg = new RegExp('[a-zA-Z0-9\- ]');
    //   let value;
    //   let name;
    //   for (let index = 0; index < len; index++) {

    //   }
    // },
    /**
     * 通过汉子获取拼音
     * @param {*} object 
     */
    // ChineseCharactersToPinYin(object) {
    //   let config = {};
    //   config.baseURL = "";
    //   Vue.http.get('/static/pinyin/pinyin.json', config).then(response => {
    //     Object.keys(response).forEach(element => {
    //       console.log(element);
    //     });
    //   });
    // }
}